package com.lilicould.controller;

import com.google.gson.Gson;
import com.lilicould.entity.Classes;
import com.lilicould.service.ClassService;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/class/*")
public class ClassController extends BaseServlet{
    public void listAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset:utf-8");
        PrintWriter out = resp.getWriter();
        String result = new ClassService().getAllClass();
        // 若不为空，说明成功获取到班级信息，则返回200状态码以及结果
        if (result != null) {
            resp.setStatus(HttpServletResponse.SC_OK);
            out.write(result);
        }else {
            // 若为空，则返回404状态码
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset:utf-8");
        PrintWriter out = resp.getWriter();
        // 获取请求体中的数据
        Classes clazz = new Gson().fromJson(req.getReader(), Classes.class);
        // 调用service层添加班级
        String result = new ClassService().addClass(clazz);
        // 若不为空说明返回了错误信息，则返回400状态码
        if (result != null) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.write(new Gson().toJson(result));
        }else {
            resp.setStatus(HttpServletResponse.SC_OK);
        }

    }

    public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset:utf-8");
        PrintWriter out = resp.getWriter();
        Gson gson = new Gson();
        Classes clazz = gson.fromJson(req.getReader(), Classes.class);

        // 获取参数
        String classCode = clazz.getClassCode();
        String majorCode = clazz.getMajorCode();
        String collegeCode = clazz.getCollegeCode();

        // 调用service层删除班级
        String result = new ClassService().deleteClass(classCode, majorCode, collegeCode);

        // 若不为空说明返回了错误信息，则返回400状态码
        if (result != null) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.write(new Gson().toJson(result));
        }else {
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    }
}
